package com.multimedia.scala
import scala.collection.mutable.ListBuffer
import scala.annotation.tailrec

object Primes {
    @tailrec
    def findSimples(maxSimple: Int, x: Int = 3, simples: ListBuffer[Int] = ListBuffer[Int](2)): ListBuffer[Int] = {

        if (x > maxSimple) return simples
  	    val maxDivisor = Math.round(Math.pow(x, 0.5))
  	    if (simples.takeWhile(_<=maxDivisor).forall(x%_!=0))
  	        simples += x
	    findSimples(maxSimple, x + 2, simples)
    }

    @tailrec
    def factor(x: Int, simples: ListBuffer[Int], acc: Map[Int, Int] = Map[Int, Int]().withDefaultValue(0)): Map[Int, Int] = {
        if (x==1) return acc
        simples.find(y=>x%y==0) match {
          case Some(y) => factor(x/y, simples, acc.updated(y, acc(y)+1))
          case None => return acc
        }
    }

    @tailrec
    def factorBig(x: BigInt, simples: ListBuffer[Int], acc: Map[Int, Int] = Map[Int, Int]().withDefaultValue(0)): Map[Int, Int] = {
        if (x==1) return acc
        simples.find(y=>x%y==0) match {
          case Some(y) => factorBig(x/y, simples, acc.updated(y, acc(y)+1))
          case None => return acc
        }
    }

    def main(args: Array[String]) {
    	//findSimples(100).foreach(println)
        println (factor(100, findSimples(100)))
        //.foreach(x=>println(x))
    }
}